package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentNoticeBinding
import com.gexiaobao.pigeon.ui.adapter.AnnouncementAdapter
import com.gexiaobao.pigeon.ui.adapter.MessageListAdapter
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityAnnouncementDetail
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 16:10
 * @Describe    : 我的组织-公告
 */
class FragmentNotice : BaseFragment<OrgDetailViewModel, FragmentNoticeBinding>() {

    private var lockOrgId = ""
    private var mDesc = ""
    private val mAdapter: MessageListAdapter by lazy { MessageListAdapter(arrayListOf()) }
    private val announcementAdapter: AnnouncementAdapter by lazy { AnnouncementAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.tvNotice.isSelected = true
        lockOrgId = requireArguments().getString("orgId").toString()
        mDesc = requireArguments().getString("desc").toString()
        mDatabind.tvOrgIntro.text = mDesc

        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(activity)
                .setBackground(R.drawable.round_b_g_5_train_fly_list_delete_red)
                .setTextColor(Color.WHITE)
                .setText(R.string.delete)
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.layoutList.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 左侧还是右侧菜单 */
//            val direction = menuBridge.direction
//            /**  菜单在Item中的Position */
//            val menuPosition = menuBridge.position
            /** 调用删除接口 */
            showLoading(getString(R.string.loading))
            mViewModel.deleteMessage(mAdapter.data[position].id.toString())
        }
        mDatabind.layoutList.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)
        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 1f))
        )

        mDatabind.layoutListAnnouncement.swipeRecyclerView.init(LinearLayoutManager(context), announcementAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 10f))
        )

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRecyclerView) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getMessageList(true, "1", lockOrgId)
            mViewModel.getRegulationAnnouncementList(true, lockOrgId.toInt())
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getMessageList(true, "1", lockOrgId)
        }

        mDatabind.layoutListAnnouncement.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getRegulationAnnouncementList(true, lockOrgId.toInt())
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_org_to_notice_detail, Bundle().apply {
                putInt("id", mAdapter.data[position].id)
            })
        }

        announcementAdapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivityAnnouncementDetail>("id" to announcementAdapter.data[position].id.toString())
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        mViewModel.getMessageList(true, "1", lockOrgId)
        mViewModel.getRegulationAnnouncementList(true, lockOrgId.toInt())
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取规程公告列表（app端） */
        mViewModel.regulationAnnouncementResult.observe(viewLifecycleOwner) {
            loadListData(
                it,
                announcementAdapter,
                loadsir,
                mDatabind.layoutListAnnouncement.swipeRecyclerView,
                mDatabind.layoutListAnnouncement.swipeRefreshLayout
            )
        }
        /**  消息列表  */
        mViewModel.messageList.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }

        /** 删除消息 */
        mViewModel.deleteMsgResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                loadsir.showLoading()
                mViewModel.getMessageList(true, "1", lockOrgId)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvNotice, mDatabind.tvRegulation, mDatabind.tvOrgDetail) {
            when (it) {
                mDatabind.tvNotice -> selectedUiState(1)
                mDatabind.tvRegulation -> selectedUiState(2)
                mDatabind.tvOrgDetail -> selectedUiState(3)
            }
        }
    }

    private fun selectedUiState(i: Int) {
        when (i) {
            1 -> {
                mDatabind.tvNotice.isSelected = true
                mDatabind.tvRegulation.isSelected = false
                mDatabind.tvOrgDetail.isSelected = false
                mDatabind.layoutList.conList.isVisible = true
                mDatabind.layoutListAnnouncement.conList.isVisible = false
                mDatabind.tvOrgIntro.isVisible = false
            }

            2 -> {
                mDatabind.tvNotice.isSelected = false
                mDatabind.tvRegulation.isSelected = true
                mDatabind.tvOrgDetail.isSelected = false
                mDatabind.layoutList.conList.isVisible = false
                mDatabind.layoutListAnnouncement.conList.isVisible = true
                mDatabind.tvOrgIntro.isVisible = false
            }

            else -> {
                mDatabind.tvNotice.isSelected = false
                mDatabind.tvRegulation.isSelected = false
                mDatabind.tvOrgDetail.isSelected = true
                mDatabind.layoutList.conList.isVisible = false
                mDatabind.layoutListAnnouncement.conList.isVisible = false
                mDatabind.tvOrgIntro.isVisible = true
            }
        }
    }

    companion object {
        fun newInstance(orgId: String, desc: String): FragmentNotice {
            val fragment = FragmentNotice()
            val bundle = Bundle()
            bundle.putString("orgId", orgId)
            bundle.putString("desc", desc)
            fragment.arguments = bundle
            return fragment
        }
    }
}